package com.isunland.managesystem.utils;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.isunland.managesystem.BuildConfig;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.MyApplication;
import com.isunland.managesystem.common.MyConst;
import com.isunland.managesystem.common.RequestManager;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.StatusProperty;
import com.isunland.managesystem.widget.CustomProgressDialog;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 工具类
 *
 * @author wangyanan
 */
@SuppressWarnings("all") public class MyUtils {

  private static final String TAG = "MyUtils";
  private static CustomProgressDialog progressDialog = null;

  public static void showDialogLoading(Activity context, int id) {
    if (context == null || id == 0) return;
    String message = context.getString(id);
    showDialogLoading(context, message);
  }

  public static void showConfirmDialog(final AppCompatActivity mActivity, String message) {
    showConfirmDialog(mActivity, message, false);
  }

  public static void showConfirmDialog(final AppCompatActivity mActivity, String message,
      final boolean finish) {
    if (mActivity == null || MyStringUtil.isEmpty(message)) return;
    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity).setMessage(message)
        .setTitle("提示")
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            // Auto-generated method stub
            if (finish) mActivity.finish();
            ;
          }
        });
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
      @Override public void onCancel(DialogInterface dialog) {
        if (finish) mActivity.finish();
        ;
      }
    });
    builder.create().show();
  }

  public static void showDialogLoading(Activity context, String message) {

    if (progressDialog == null) {
      progressDialog = CustomProgressDialog.createDialog(context);
    }
    try {
      progressDialog.setMessage(message);

      progressDialog.show();
    } catch (Exception e) {

    }
  }

  public static void showDialogLoading(Activity context) {
    showDialogLoading(context, R.string.loading);
    BtnClickUtil.isFastDoubleClick();
  }

  /**
   * 关闭Dialog提示
   */
  public static void dismissDialog() {
    try {
      if (progressDialog != null) {
        progressDialog.dismiss();
        progressDialog = null;
      }
    } catch (Exception e) {
      // Auto-generated catch block
      e.printStackTrace();
    }
  }

  /**
   * Toast提示消息
   */
  public static void show(Context context, String message) {
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  }

  /**
   * Toast提示消息
   */
  public static void show(Context context, int message) {
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  }

  /**
   * 输出Log调试信息
   */
  public static void i(String TAG, String message) {
    LogUtil.i(TAG, message);
  }

  public static void e(String TAG, String message, Exception e) {
    Log.e(TAG, message, e);
  }

  /**
   * 判断手机是否联网
   *
   * @return boolean
   */
  public static boolean isNetLink(Context context) {
    // 为什么需要两处代码检查呢？
    // 在Android旧版本系统中，应检查 getBackgroundDataSetting()方法的返回结果，
    // 如果返回结果为 false ，表示不允许使用后台数据，那我们也就解脱了。
    // 当然，如果不去检查，也能随意使用后台数据。但这样做很可能会出问题（电量耗光或应用运行缓慢）。
    // 而在Android 4.0（Ice Cream Sandwich）中，后台数据设置直接会禁用网络。这也是为什么需
    // 要检查 getActiveNetworkInfo() 方法是否返回空值的原因。如果返回为空，则网络不可用。对
    // 用户来说，这是好事，因为这意味着后台数据设置总是按用户的预期行事。
    ConnectivityManager cm = (ConnectivityManager) MyApplication.getAppContext()
        .getSystemService(Context.CONNECTIVITY_SERVICE);
    @SuppressWarnings("deprecation") boolean isNetworkAvialable =
        cm.getBackgroundDataSetting() && cm.getActiveNetworkInfo() != null;
    return isNetworkAvialable;
    // try {
    // ConnectivityManager connectivityManager = (ConnectivityManager)
    // context
    // .getSystemService(Context.CONNECTIVITY_SERVICE);
    // if (connectivityManager != null) {
    // NetworkInfo info = connectivityManager.getActiveNetworkInfo();
    // if (info != null && info.isConnected()
    // && info.getState() == NetworkInfo.State.CONNECTED) {
    // return true;
    // }
    // }
    // } catch (Exception e) {
    // return false;
    // }
    // return false;
  }

  public static String changeNotArrayDateToJson(String a, String b, String c, String d) {
    JSONObject object = null;
    object = new JSONObject();
    try {
      object.put(a, b); // 把数据加入JSONObject对象即可�?userid"相当于map里面的key,1即为value的�?�?
      object.put(c, d);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    String jsonString = null;
    jsonString = object.toString();// 把JSONObject转换成json格式的字符串
    return jsonString;
  }

  /**
   * 弹出对话框提示用户联�?
   */
  // public static void showNetLink(final Context context)
  // {
  // AlertDialog.Builder builder = new AlertDialog.Builder(context);
  // builder.setTitle(context.getResources().getString(R.string.no_linknet_dialog_title));
  // builder.setMessage(context.getResources().getString(R.string.no_linknet_dialog_message));
  // builder.setPositiveButton(context.getResources().getString(R.string.no_linknet_dialog_setnet),
  // new OnClickListener()
  // {
  // public void onClick(DialogInterface dialog, int which)
  // {
  // dialog.cancel();
  // context.startActivity(new
  // Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
  // }
  // });
  // builder.setNegativeButton(context.getResources().getString(R.string.back),
  // new OnClickListener()
  // {
  // public void onClick(DialogInterface dialog, int which)
  // {
  // dialog.cancel();
  // }
  // }).show();
  // }
  public static boolean isJsonCorrect(String content) {
    if (content == null) return false;
    String status;
    try {
      status = new JSONObject(content).getString("status");
    } catch (JSONException e) {

      e.printStackTrace();
      return false;
    }
    if ("0".equals(status)) {

      return false;
    }
    return true;
  }

  /**
   * 将获取的用户id装换为int型数�?
   */

  public static int getIntByUserid(String string) {
    if (TextUtils.isEmpty(string)) {

      return -1;
    } else {

      return Integer.parseInt(string);
    }
  }

  public static long parseDate(String date) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
      return formatter.parse(date).getTime();
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }

  /**
   * 使用Myutils.valueOfDouble
   */
  @Deprecated public static Double stringToDouble(String string) {
    return Double.parseDouble(string);
  }

  public static String parse(long date) {
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(date));
  }

  public static String parse2(long date) {
    return new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date(date));
  }

  /**
   * 比较与当前时间大小差�?
   *
   * @throws ParseException 时间格式错误
   */
  public static long LargerThanNow(String time) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date;
    try {
      date = df.parse(time);
    } catch (ParseException e) {
      // Auto-generated catch block
      e.printStackTrace();
      Log.e(TAG, "时间格式错误");
      return 0;
    }
    return date.getTime() - System.currentTimeMillis();
  }

  // 将字符串进行MD5加密，获取相应的加密代码
  public static String getMD5(String content) {

    try {

      MessageDigest digest = MessageDigest.getInstance("MD5");

      digest.update(content.getBytes());

      return getHashString(digest);
    } catch (Exception e) {

    }

    return null;
  }

  private static String getHashString(MessageDigest digest) {

    StringBuilder builder = new StringBuilder();

    for (byte b : digest.digest()) {

      builder.append(Integer.toHexString((b >> 4) & 0xf));

      builder.append(Integer.toHexString(b & 0xf));
    }

    return builder.toString().toUpperCase();
  }

  /**
   * 将字符串中的中文转化为拼,其他字符不变
   */
    /*
     * public static String getPingYin(String inputString) {
	 * HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
	 * format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
	 * format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
	 * format.setVCharType(HanyuPinyinVCharType.WITH_V); char[] input =
	 * inputString.trim().toCharArray(); String output = ""; try { for (char
	 * curchar : input) { if (java.lang.Character.toString(curchar).matches(
	 * "[\\u4E00-\\u9FA5]+")) { String[] temp =
	 * PinyinHelper.toHanyuPinyinStringArray( curchar, format); output +=
	 * temp[0]; } else output += java.lang.Character.toString(curchar); } }
	 * catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); }
	 * return output; }
	 * 
	 * // 汉字转换为汉语拼音首字母，英文字符?
	 * 
	 * public static String getFirstSpell(String chinese) { StringBuffer pybf =
	 * new StringBuffer(); char[] arr = chinese.toCharArray();
	 * HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
	 * defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
	 * defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (char
	 * curchar : arr) { if (curchar > 128) { try { String[] temp =
	 * PinyinHelper.toHanyuPinyinStringArray( curchar, defaultFormat); if (temp
	 * != null) { pybf.append(temp[0].charAt(0)); } } catch
	 * (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else
	 * { pybf.append(curchar); } } return pybf.toString().replaceAll("\\W",
	 * "").trim(); }
	 */
  public static String getUncaughtException(Throwable throwable) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    throwable.printStackTrace(printWriter);
    printWriter.close();
    String uncaughtException = stringWriter.toString();
    return uncaughtException;
  }

  /**
   * 读取本地asset文件为字符串.常用于本地测试.
   */
  public static String readAssetsFile(Context mContext, String fileName) {

    BufferedReader reader = null;
    try {
      InputStream in = mContext.getAssets().open(fileName);
      // FileInputStream in = mContext.openFileInput(fileName);
      reader = new BufferedReader(new InputStreamReader(in));
      StringBuilder jsonString = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        jsonString.append(line);
      }

      return jsonString.toString();
    } catch (Exception e) {
      LogUtil.e(TAG, "error", e);
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          LogUtil.e(TAG, "error", e);
        }
      }
    }
    return null;
  }

  public static boolean isEmail(String email) {
    if (email == null) return false;
    String str = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
    Pattern p = Pattern.compile(str);
    Matcher m = p.matcher(email);
    return m.matches();
  }

  public static boolean isUrl(String url) {
    String str =
        "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";
    Pattern p = Pattern.compile(str);
    Matcher m = p.matcher(url);
    return m.matches();
  }

  public static String getSDPath() {
    File sdDir = null;
    boolean sdCardExist =
        Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
    if (sdCardExist) {
      sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
    }
    return sdDir.toString();
  }

  public static boolean isServiceRunning(Context context, String serviceName) {
    if (!TextUtils.isEmpty(serviceName) && context != null) {
      ActivityManager activityManager =
          (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
      ArrayList<RunningServiceInfo> runningServiceInfoList =
          (ArrayList<RunningServiceInfo>) activityManager.getRunningServices(100);
      for (Iterator<RunningServiceInfo> iterator = runningServiceInfoList.iterator();
          iterator.hasNext(); ) {
        RunningServiceInfo runningServiceInfo = (RunningServiceInfo) iterator.next();
        if (serviceName.equals(runningServiceInfo.service.getClassName().toString())) {
          return true;
        }
      }
    } else {
      return false;
    }
    return false;
  }

  public static boolean isPhoneNumber(String number) {
    String phoneNumber = number;
    if (phoneNumber == null || phoneNumber.length() != 11) {
      return false;
    }
    return true;
  }

  /**
   * textview是否为空.
   */
  public static boolean isEmptyText(TextView tv) {
    return tv.getText().toString().trim().isEmpty();
  }

  /* 检查字符串是否为电话号码的方法,并返回true or false的判断值 */
  @Deprecated public static boolean isPhoneNumberValid(String phoneNumber) {
    boolean isValid = false;
        /*
         * 可接受的电话格式有: ^\\(? : 可以使用 "(" 作为开头 (\\d{3}): 紧接着三个数字 \\)? : 可以使用")"接续
		 * [- ]? : 在上述格式后可以使用具选择性的 "-". (\\d{4}) : 再紧接着三个数字 [- ]? : 可以使用具选择性的
		 * "-" 接续. (\\d{4})$: 以四个数字结束. 可以比较下列数字格式: (123)456-78900,
		 * 123-4560-7890, 12345678900, (123)-4560-7890
		 */
    String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$";
    String expression2 = "^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
    CharSequence inputStr = phoneNumber;
        /* 创建Pattern */
    Pattern pattern = Pattern.compile(expression);
        /* 将Pattern 以参数传入Matcher作Regular expression */
    Matcher matcher = pattern.matcher(inputStr);
        /* 创建Pattern2 */
    Pattern pattern2 = Pattern.compile(expression2);
        /* 将Pattern2 以参数传入Matcher2作Regular expression */
    Matcher matcher2 = pattern2.matcher(inputStr);
    if (matcher.matches() || matcher2.matches()) {
      isValid = true;
    }
    return isValid;
  }

  // 判断是否是数字

  public static boolean isNumber(String numberStr) {
    if (numberStr == null) {
      throw new NullPointerException();
    }
    try {
      Double.parseDouble(numberStr);
    } catch (NumberFormatException e) {
      return false;
    }

    return true;
  }

  ;

  /**
   * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
   */
  public static int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
  }

  /**
   * 将字符串逗号拆分为LIst<String>
   * 使用MyStringUtils.splitStr()t替代
   */
  @Deprecated public static List<String> getListString(String originalText) {
    if (originalText == null || originalText.equals("")) {
      return null;
    }
    List<String> tags = new ArrayList<String>();
    // 逗号的位置,保存第一个逗号的位置.
    int indexOfComma = originalText.indexOf(',');
    String tag;
    while (indexOfComma != -1) {
      // 第一个逗号之前是拆分后的字符串.
      tag = originalText.substring(0, indexOfComma);
      tags.add(tag);
      //
      originalText = originalText.substring(indexOfComma + 1);
      indexOfComma = originalText.indexOf(',');
    }

    tags.add(originalText);
    return tags;
  }

  /**
   * 是否开发者模式.
   */
  public static boolean isDevelopMode(Context context) {
    if (context == null) return false;
    return SharedPreferencesUtil.getBoolean(context, SharedPreferencesUtil.KEY_DEVELOP, false);
  }

  /**
   * 设置开发者模式
   */
  public static void setDevelopMode(Context context, boolean isDev) {
    if (context == null) return;
    SharedPreferencesUtil.setBoolean(context, SharedPreferencesUtil.KEY_DEVELOP, isDev);
  }

  /**
   * 获取登陆人名单
   */
  public static LinkedHashMap<String, String> getUserNames() {
    try {
      Object result = FileUtil.readFromFile(new File(FileUtil.getExternalDir(), "name.xinpuda"));
      return (LinkedHashMap) result;
    } catch (Exception e) {
      return null;
    }
  }

  /**
   * 增加登陆人
   */
  public static void addUser(String name, String value) {
    if (TextUtils.isEmpty(name) || TextUtils.isEmpty(value)) return;
    LinkedHashMap<String, String> names = getUserNames();
    if (names == null) names = new LinkedHashMap<>();
    names.put(name, value);
    FileUtil.writeToFile(names, new File(FileUtil.getExternalDir(), "name.xinpuda"));
  }

  public static void addPath(String path) {
    if (TextUtils.isEmpty(path)) return;
    ArrayList<String> paths = getServerPaths();
    if (paths == null) paths = new ArrayList<>();
    if (paths.contains(path)) return;
    paths.add(path);
    //去重
    HashSet h = new HashSet(paths);
    paths.clear();
    paths.addAll(h);
    FileUtil.writeToFile(paths, new File(FileUtil.getExternalDir(), "path.xinpuda"));
  }

  /**
   * 获取服务器路径
   */
  public static ArrayList<String> getServerPaths() {
    try {
      Object resultPath =
          FileUtil.readFromFile(new File(FileUtil.getExternalDir(), "path.xinpuda"));
      return (ArrayList<String>) resultPath;
    } catch (Exception e) {
      return null;
    }
  }

  /**
   * 字符串逗号拼接成String
   * 使用MyStringUtil.joinStr代替
   */
  @Deprecated public static String getJoinString(List<String> tags) {
    if (tags == null || tags.size() == 0) {
      return null;
    }
    StringBuilder sb = new StringBuilder();
    for (String str : tags) {
      sb.append(str).append(",");
    }
    String joinStr = sb.substring(0, sb.length() - 1).toString();
    LogUtil.i(joinStr);
    return joinStr;
  }

  /**
   * @return String
   * @Title: getSingleQuotesString
   * @Description: 字符串拼接单引号''
   */
  public static List<String> getSingleQuotesString(List<String> tags) {
    if (tags == null || tags.size() == 0) {
      return null;
    }
    List<String> newList = new ArrayList<String>();
    for (String str : tags) {
      newList.add("'" + str + "'");
    }

    return newList;
  }

  /**
   * @return String
   * @Title: getSingleQuotesString
   * @Description: 字符串拼接单引号''
   */
  public static String getSingleQuotesString(String tag) {
    // 拆分
    List<String> list = getListString(tag);
    // 拼接单引号''
    list = getSingleQuotesString(list);
    // 拼接.
    return getJoinString(list);
  }

  /**
   * 获取<meta-data>中保存的值
   */
  public static String getMetaValue(Context context, String metaKey) {
    Bundle metaData = null;
    String apiKey = null;
    // 非空直接返回空.
    if (context == null || metaKey == null) {
      return null;
    }
    try {
      ApplicationInfo ai = context.getPackageManager()
          .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
      if (null != ai) {
        metaData = ai.metaData;
      }
      if (null != metaData) {
        // AndroidManifest中数据保存在ApplicationInfo的metaData成员变量中.
        apiKey = metaData.getString(metaKey);
      }
    } catch (NameNotFoundException e) {

    }
    return apiKey;
  }

  // {"pass":"4355","name":"12342","wang":"fsf"}
  @Deprecated public static HashMap<String, String> toHashMap(String str) {

    HashMap<String, String> map = new HashMap<String, String>();
    JSONObject jObject = null;
    try {
      jObject = new JSONObject(str);
    } catch (Exception e) {
      e.printStackTrace();
      LogUtil.e("json解析异常");
      return map;
    }

    Iterator<?> keys = jObject.keys();

    while (keys.hasNext()) {
      String key = (String) keys.next();
      String value = null;
      try {
        value = jObject.getString(key);
      } catch (JSONException e) {
        e.printStackTrace();
        continue;
      }
      map.put(key, value);
    }

    //System.out.println("json : "+jObject);
    //System.out.println("map : "+map);

    //String sb = str.substring(1, str.length() - 1);
    //String[] name = sb.split(",");
    //String[] nn = null;
    //HashMap<String, String> map = new HashMap<String, String>();
    //for (int i = 0; i < name.length; i++) {
    //    nn = name[i].split(":");
    //    map.put(nn[0].replaceAll("\"", ""), nn[1].replaceAll("\"", ""));
    //}
    return map;
  }

  public static HashMap<String, String> JsontoHashMap(String str) {

    ParamsNotEmpty params = new ParamsNotEmpty();
    JSONObject jObject = null;
    try {
      jObject = new JSONObject(str);
    } catch (Exception e) {
      e.printStackTrace();
      LogUtil.e("json解析异常");
      return params.getParams();
    }

    Iterator<?> keys = jObject.keys();

    while (keys.hasNext()) {
      String key = (String) keys.next();
      String value = null;
      try {
        value = jObject.getString(key);
      } catch (JSONException e) {
        e.printStackTrace();
        continue;
      }
      params.put(key, value);
    }
    return params.getParams();
  }

  /**
   * 不同数据状态显示不同.
   */
  public static void switchDataStutus(Context context, TextView tv, String dataStatus) {
    switchShadowStutus(context, tv, dataStatus);
  }

  public static void switchShadowStutus(Context context, TextView tv, String dataStatus) {
    switchShadowStutus(context, tv, dataStatus, null);
  }

  /**
   * 不同数据状态显示不同.
   *
   * @SuppressWarnings("ResourceType")
   */
  @SuppressWarnings("all") public static void switchShadowStutus(Context context, TextView tv,
      String dataStatus, String dataStatusName) {
    if (tv == null || context == null) return;
    StatusProperty dataProperty = null;

    if (dataStatus != null && DataStatus.map.containsKey(dataStatus)) {
      dataProperty = DataStatus.map.get(dataStatus);
    }
    tv.setTextColor(context.getResources()
        .getColor(dataProperty != null ? dataProperty.getTextColor() : R.color.dark_grey));
    tv.setText((dataProperty != null && dataStatusName == null) ? dataProperty.getStatusName()
        : dataStatusName);
  }

  @SuppressWarnings("deprecation") public static int getColor(Context context, int resColorId) {
    try {
      return context.getResources().getColor(resColorId);
    } catch (Resources.NotFoundException e) {
      e.printStackTrace();
      return context.getResources().getColor(R.color.dark_grey);
    }
  }

  /**
   * @return String
   * @Title: doubleToStr
   * @Description: Double类型的返回值无法直接设置到页面, 必须转化为字符串.
   */
  public static String doubleToStr(Double d) {
    if (d == null) {
      return null;
    }

    return d + "";
  }

  /**
   * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
   *
   * @return true 表示开启
   */
  public static final boolean isOPen(final Context context) {
    LocationManager locationManager =
        (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
    boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
    boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (gps || network) {
      return true;
    }

    return false;
  }

  /**
   * 强制帮用户打开GPS
   */
  public static final void openGPS(Context context) {
    Intent GPSIntent = new Intent();
    GPSIntent.setClassName("com.android.settings",
        "com.android.settings.widget.SettingsAppWidgetProvider");
    GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
    GPSIntent.setData(Uri.parse("custom:3"));
    try {
      PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
    } catch (CanceledException e) {
      e.printStackTrace();
    }
  }

  //版本名
  public static String getVersionName(Context context) {
    try {
      return getPackageInfo(context).versionName;
    } catch (Exception e) {
      return "";
    }
  }

  //版本号
  public static int getVersionCode(Context context) {
    try {
      return getPackageInfo(context).versionCode;
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }

  private static PackageInfo getPackageInfo(Context context) {
    PackageInfo pi = null;

    try {
      PackageManager pm = context.getPackageManager();
      pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);

      return pi;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return pi;
  }

  public static String getPackageName(Context context) {
    if (context == null) return "";
    return context.getPackageName();
  }

  public static boolean checkPermission(Context context, String permission) {
    boolean result = false;
    //		if (Build.VERSION.SDK_INT >= 23) {
    //			if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
    //				result = true;
    //			}
    //		} else {
    PackageManager pm = context.getPackageManager();
    if (pm.checkPermission(permission, context.getPackageName())
        == PackageManager.PERMISSION_GRANTED) {
      result = true;
      //			}
    }
    return result;
  }

  public static String getDeviceInfo(Context context) {
    try {
      org.json.JSONObject json = new org.json.JSONObject();
      android.telephony.TelephonyManager tm =
          (android.telephony.TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      String device_id = null;
      if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
        device_id = tm.getDeviceId();
      }
      android.net.wifi.WifiManager wifi =
          (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);
      String mac = wifi.getConnectionInfo().getMacAddress();
      json.put("mac", mac);
      if (TextUtils.isEmpty(device_id)) {
        device_id = mac;
      }
      if (TextUtils.isEmpty(device_id)) {
        device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
            android.provider.Settings.Secure.ANDROID_ID);
      }
      json.put("device_id", device_id);
      return json.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 基本信息
   *
   * @return 基本信息
   */
  public static String getBasicInfo(Context context) {
    String handSetInfo =
        "用户名："
            + CurrentUser.newInstance(context).getName()
            + ",密码："
            + CurrentUser.newInstance(context).getPassword()
            + ",版本号:"
            + MyUtils.getVersionCode(context)
            + ",版本名:"
            + MyUtils.getVersionName(context)
            + "手机型号:"
            + android.os.Build.MODEL
            + ",SDK版本:"
            + android.os.Build.VERSION.SDK
            + ",系统版本:"
            + android.os.Build.VERSION.RELEASE;
    return handSetInfo;
  }

  //mock测试
  public static String getHelloWorldString(Context context) {
    return context.getString(R.string.app_name);
  }

  // 获取手机状态栏高度
  public static int getStatusBarHeight(Context context) {
    Class<?> c = null;
    Object obj = null;
    Field field = null;
    int x = 0, statusBarHeight = 0;
    try {
      c = Class.forName("com.android.internal.R$dimen");
      obj = c.newInstance();
      field = c.getField("status_bar_height");
      x = Integer.parseInt(field.get(obj).toString());
      statusBarHeight = context.getResources().getDimensionPixelSize(x);
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    return statusBarHeight;
  }

  /**
   * 为19以上版本的标题栏遮住了状态栏设置顶部边距。
   */
  public static void setPaddingTop(View view, int top) {
    if (view == null) return;

    view.setPadding(view.getPaddingLeft(), top, view.getPaddingRight(), view.getPaddingBottom());
  }

  public static void setFitWindow(View view) {
    if (view == null) return;

    view.setFitsSystemWindows(true);
  }

  /**
   * 获取设备id.
   */
  public static String getDeviceId(Context context) {
    String id = SharedPreferencesUtil.getString(context, SharedPreferencesUtil.DEVICE_ID, "");
    if (TextUtils.isEmpty(id)) {
      TelephonyManager manager =
          (TelephonyManager) context.getSystemService(Activity.TELEPHONY_SERVICE);
      id = manager.getDeviceId();
      if (TextUtils.isEmpty(id)) {

        id = "";
        ToastUtil.show(R.string.imisNotNull);
      } else {
        SharedPreferencesUtil.setString(context, SharedPreferencesUtil.DEVICE_ID, id);
      }
    }
    return id;
  }

  /**
   * 获取wifi信息
   */
  public static WifiInfo getWifiInfo(Context context) {
    ConnectivityManager connectionManager = (ConnectivityManager) MyApplication.getAppContext()
        .getSystemService(Context.CONNECTIVITY_SERVICE);
    @SuppressWarnings("deprecation") NetworkInfo networkInfo =
        connectionManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    //只有已连接才去取值,个别手机又假连接现象.否则会取出类似0x,00:00:00:00:00这样的结果.
    if (networkInfo.isConnected()) {
      WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

      return wifiManager.getConnectionInfo();
    }
    return null;
  }

  //判断WiFi是否打开
  public static boolean isWifiEnabled(Context context) {
    WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    return manager.isWifiEnabled();
  }

  /**
   * 拼接服务端需要的wifi参数
   *
   * @return 名称+id  ,如果没有就返回空字符串.
   */
  public static String getWifiParams(WifiInfo info) {
    //wifi有效性验证.

    if (info == null) return "";
    String bssid = info.getBSSID();
    String ssid = info.getSSID();
    if ((TextUtils.isEmpty(bssid)) || (TextUtils.isEmpty(ssid))) {

      return "";
    }
    //过滤无效的mac地址,产生的原因是个别手机假连接.
    if (bssid.equals("00:00:00:00:00:00")) {
      return "";
    }
    //ssid中包含斜线，替换为空。
    ssid = ssid.replaceAll("\"", "");
    LogUtil.i("ssid+\",\"+bssid");
    return ssid + "," + bssid;
  }

  /**
   * 类型安全的转换函数.
   * 使用MyStringUtil里的同名方法
   *
   * @param value 待转换
   * @param defaultValue 默认值
   * @return 数字.
   */
  @Deprecated public final static double valueOfDouble(Object value, double defaultValue) {
    if (value == null || "".equals(value.toString().trim())) {
      return defaultValue;
    }
    try {
      return Double.valueOf(value.toString());
    } catch (NumberFormatException e) {
      return defaultValue;
    }
  }

  /** 获取本机号码 */
  public static String getPhoneNumber(Context context) {
    TelephonyManager mTelephonyMgr =
        (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    return mTelephonyMgr.getLine1Number();
  }

  /*** 是不是韦加环境 */
  public static boolean isWeiJia() {
    return MyStringUtil.equals(BuildConfig.FLAVOR, MyConst.FLAVOR_WEIJIA);
  }

  /*** 是不是国欣环境 */
  public static boolean isGuoXin() {
    return MyStringUtil.equals(BuildConfig.FLAVOR, MyConst.FLAVOR_GUOXIN);
  }

  public static Spanned getAppNameHtml(Context context) {
    if (context == null) return null;
    String appName = context.getResources().getString(R.string.app_name);
    if (appName.contains("+")) appName = appName.replace("+", "<sup>+</sup>");
    return Html.fromHtml(appName);
  }

  /** 是否开启BugTags */
  public static boolean isBugTags(Context context) {
    boolean isBugTags =
        SharedPreferencesUtil.getBoolean(context, SharedPreferencesUtil.KEY_IS_BUGTAGS, false);
    return isBugTags || ((!isBugTags) && BuildConfig.IS_BUGTAGS);
  }

  /** 是否开启推送 */
  public static boolean isPush(Context context) {
    boolean isPush =
        SharedPreferencesUtil.getBoolean(context, SharedPreferencesUtil.KEY_IS_PUSH, false);
    return isPush || ((!isPush) && BuildConfig.IS_PUSH);
  }

  /** 是否打印日志 */
  public static boolean isLog(Context context) {
    boolean isLog =
        SharedPreferencesUtil.getBoolean(context, SharedPreferencesUtil.KEY_IS_LOG, false);
    return isLog || ((!isLog) && BuildConfig.IS_LOG);
  }

  public static ArrayList<String> getActivitiesName(Activity context) {
    try {
      ActivityInfo[] activities = context.getPackageManager()
          .getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES).activities;
      if (activities == null || activities.length == 0) return null;
      ArrayList<String> result = new ArrayList<>();
      for (ActivityInfo activityInfo : activities) {
        result.add(activityInfo.name);
        //if ((!MyStringUtil.isEmpty(fullName)) && fullName.contains(".")) {
        //  result.add(fullName.substring(fullName.lastIndexOf(".")+1, fullName.length()));
        //}
      }
      return result;
    } catch (NameNotFoundException e) {
      e.printStackTrace();
      return null;
    }
  }

  public static boolean isMock() {
    return SharedPreferencesUtil.getBoolean(MyApplication.getAppContext(),
        SharedPreferencesUtil.KEY_IS_MOCK, false);
  }

  public static void chooseFile(Fragment fragment, int requestCode) {
    if (fragment == null) return;
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    fragment.startActivityForResult(Intent.createChooser(intent2,
        fragment.getActivity().getString(R.string.chooseFileExplorer)), requestCode);
  }

  /** 解决html图文混排的图片自适应 */
  public static String parseWebImage(String html) {
    //html就是解析到服务器返回的图文混排html标签内容:
    if (TextUtils.isEmpty(html)) {
      return "";
    }
    Document parse = Jsoup.parse(html);
    Elements imgs = parse.getElementsByTag("img");
    if (!imgs.isEmpty()) {
      for (Element e : imgs) {
        imgs.attr("width", "100%");
        imgs.attr("height", "auto");
      }
    }
    String content = parse.toString();
    return content;
  }

  /**
   * 将cookie同步到WebView
   *
   * @return true 同步cookie成功，false同步cookie失败
   */
  public static boolean syncCookie(Context mActivity) {
    if (mActivity == null) return false;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
      //noinspection deprecation
      CookieSyncManager.createInstance(mActivity);
    }
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setCookie(ApiConst.getUrlMain(),
        RequestManager.getCookie());//如果没有特殊需求，这里只需要将session id以"key=value"形式作为cookie即可
    String newCookie = cookieManager.getCookie(ApiConst.getUrlMain());
    return !TextUtils.isEmpty(newCookie);
  }

  public static <T> T inflate(String json, Class<T> type) {
    try {
      return new Gson().fromJson(json, type);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
}
